/*
 * @Author: chen17
 * @Date: 2022-03-14 16:25:36
 * @LastEditTime: 2023-10-15 08:40:44
 * @Description: 工具函数
 */

const Layout = () => import('@/layout')
const modules = require.context('../views', true, /\.vue/)

/*
 * 防抖
 * fn [function] 需要防抖的函数
 * delay [number] 毫秒，防抖期限值
 * eg. getCouponMethod: debounce(function() {}, 1000)
 */
export const debounce = (fn, delay) => {
    let timer = null //借助闭包
    return function () {
        let that = this
        let args = arguments
        if (timer) {
            clearTimeout(timer) //进入该分支语句，说明当前正在一个计时过程中，并且又触发了相同事件。所以要取消当前的计时，重新开始计时
        }
        timer = setTimeout(function () {
            fn.apply(that, args)
        }, delay) // 进入该分支说明当前并没有在计时，那么就开始一个计时
    }
}

/*
 * 节流
 * fn [function] 需要节流的函数
 * delay [number] 毫秒，节流期限值
 * eg. getCouponMethod: debounce(function() {}, 1000)
 */
export const throttle = (fn, delay) => {
    let valid = true
    return function () {
        let that = this
        let args = arguments
        if (!valid) {
            //休息时间 暂不接客
            return false
        }
        // 工作时间，执行函数并且在间隔期内把状态位设为无效
        valid = false
        setTimeout(() => {
            fn.apply(that, args)
            valid = true
        }, delay)
    }
}

/**
 * @description 图片上传生成唯一id
 * @returns {string}
 */
export function genNonDuplicateID(randomLength) {
    return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
}

/**
 * @description 截取文件名称及后缀
 * @param url
 * @returns {String}
 */
export function getFileName(url) {
    if (!url) return
    let dividingLine = '|'
    let lastIndex = url.lastIndexOf('/')
    let fileName = url.substring(lastIndex + 1)
    let dividingLineIndex = fileName.indexOf(dividingLine)
    if (dividingLineIndex !== -1) {
        return fileName.substring(fileName.lastIndexOf(dividingLine) + 1)
    } else {
        return fileName
    }
}

/**
 * @description 判断是否为空
 * @param str
 * @returns {boolean}
 */
export function isBlank(str) {
    if (str === 0) {
        return false
    } else {
        return str === null || str === '' || str === false
    }
}

/**
 * @description 异步加载js
 * @param url
 * @returns {callback}
 */
export function loadScript(url, callback) {
    let script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = 'async'
    script.src = url
    document.body.appendChild(script)
    if (script.readyState) {
        //IE
        script.onreadystatechange = function () {
            if (script.readyState == 'complete' || script.readyState == 'loaded') {
                script.onreadystatechange = null
                callback()
            }
        }
    } else {
        //非IE
        script.onload = function () {
            callback()
        }
    }
}

/**
 * @description 递归处理修改符合条件的路由
 * @param routes
 * @returns {Array}
 */
export function dealRoutes(constantRoutes, apiRoutes) {
    constantRoutes.forEach(item => {
        // 处理本地路由对应的访问权限
        apiRoutes.forEach(ele => {
            if (item.path === ele.path) {
                item.meta.title = ele.name
                item.meta.icon = ele.icon
                item.meta.permList = ele.permList || []
                item.hasPermission = true
                if (item.component === 'Layout') {
                    item.component = Layout
                } else {
                    item.component = modules(`.${item.path}.vue`).default
                }
                if (item.hasOwnProperty('children') && ele.hasOwnProperty('children')) dealRoutes(item.children, ele.children)
            }
        })
        // 父级路由的redirect为子路由的第一项的path
        if (item.parentId === 0 && item.children && item.children.length) {
            let filterRoutes = item.children.filter(route => route.hasPermission)
            item.redirect = filterRoutes.length ? filterRoutes[0].path : ''
        }
    })
    return constantRoutes
}

/**
 * @description 过滤符合条件的路由
 * @param routes
 * @returns {Array}
 */
export function filterPermissionRoutes(routes) {
    return routes.filter(item => {
        if (item.hasOwnProperty('children')) {
            item.children = filterPermissionRoutes(item.children)
        }
        return item.hasPermission === true
    })
}

/**
 * @description 平级转树级菜单
 * @param routes
 * @returns {Array}
 */
export function arrayToTree(array, parentId = 0) {
    let tree = []
    array.forEach(item => {
        if (item.parentId === parentId) {
            item['children'] = arrayToTree(array, item.menuId)
            tree.push(item)
        }
    })
    return tree
}

/**
 * @description 树级菜单转平级
 * @param routes
 * @returns {Array}
 */
export function treeToArray(treeData, childKey = 'children') {
    let result = []
    for (let key in treeData) {
        let obj = treeData[key]
        let clone = JSON.parse(JSON.stringify(obj))
        delete clone[childKey]
        result.push(clone)
        if (obj[childKey]) {
            let tmp = treeToArray(obj[childKey], childKey)
            result = result.concat(tmp)
        }
    }
    return result
}

/**
 * @description 深拷贝
 * @param obj
 * @returns {Object}
 */
export function deepClone(obj) {
    //判断传进来的参数类型不是对象数组 或者是null时 直接返回
    if (typeof obj !== 'object' || obj == null) {
        return obj
    }
    //定义返回值result
    // 判断传进来的数据类型 是数组/对象 就给result一个数组/对象
    let result = Array.isArray(obj) ? [] : {}
    //循环遍历方便拷贝
    for (let key in obj) {
        //判读自有属性
        if (obj.hasOwnProperty(key)) {
            //函数递归实现深层拷贝
            result[key] = deepClone(obj[key])
        }
    }
    //返回出去
    return result
}

// 判断两个对象是否完全一致
export function isObjEqual(obj1, obj2) {
    if (obj1 === obj2) return true
    if (typeof obj1 !== 'object' || typeof obj2 !== 'object' || obj1 === null || obj2 === null) return false
    const keys1 = Object.keys(obj1)
    const keys2 = Object.keys(obj2)
    if (keys1.length !== keys2.length) return false
    for (let key of keys1) {
        if (!keys2.includes(key) || !isObjEqual(obj1[key], obj2[key])) {
            return false
        }
    }
    return true
}

// 拼接对象省市区地址
export function concatObjPcdsAddress(data, keys = ['province', 'city', 'district', 'street']) {
    let pcdsAddress = ''
    keys.forEach(key => {
        if (data[key]) pcdsAddress += ' ' + data[key]
    })
    console.log(pcdsAddress, 'pcdsAddress')
    return pcdsAddress
}

// 拼接数组省市区地址
export function concatArrayPcdsAddress(list, keys = ['province', 'city', 'district', 'street']) {
    let obj = {}
    let pcdsAddress = ''
    list.forEach((item, index) => {
        if (item.name) {
            obj[keys[index]] = item.name
            pcdsAddress += ' ' + item.name
        } else {
            obj[keys[index]] = ''
        }
    })
    console.log(obj, 'obj')
    console.log(pcdsAddress, 'pcdsAddress')
    return { obj, pcdsAddress }
}
